package wangjg.android.test;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;

import wangjg.android.R;

import android.app.Activity;
import android.net.LocalServerSocket;
import android.net.LocalSocket;
import android.net.LocalSocketAddress;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class LocalSocketActivity extends Activity {
	
	private static final String NAME = "lss-test";
	private LocalServerSocket lss ;
	private boolean hold = true;
	private List<LocalSocket> receivedClients = new ArrayList<LocalSocket>();
	
	private LocalSocket clientLocalSocket1;
	private LocalSocket clientLocalSocket2;
	
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.main);
        this.init();
        this.startServer();
        try {
			Thread.sleep(1000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
        this.startClient();
	}
	
	OnClickListener btn_button1_listener=new OnClickListener(){
		public void onClick(View v) {
			sendLocalSocket(clientLocalSocket1,"hello");
		}
    };
    
	OnClickListener btn_button2_listener=new OnClickListener(){
		public void onClick(View v) {
			for(LocalSocket ls : receivedClients){
				sendLocalSocket(ls, "i am server.");
			}
		}
    };
    
	OnClickListener btn_button3_listener=new OnClickListener(){
		public void onClick(View v) {
			
		}
    };
    
	private void init(){
	    Button btn_button1=(Button)findViewById(R.id.button1);
	    btn_button1.setOnClickListener(btn_button1_listener);
	    
	    Button btn_button2=(Button)findViewById(R.id.button2);
	    btn_button2.setOnClickListener(btn_button2_listener);
	    
	    Button btn_button3=(Button)findViewById(R.id.button3);
	    btn_button3.setOnClickListener(btn_button3_listener);
	}
	
	public void onStop(){
		super.onStop();
		this.stopServer();
	}
	
	private void startServer() {
		Thread t = new Thread(){
			public void run(){
				Log.i(getClass().getName(), "listening...");
		        try {
					lss = new LocalServerSocket(NAME);
					Log.d(getClass().getName(), lss.getFileDescriptor().toString());
					while(hold){
						LocalSocket ls = lss.accept();
						receivedClients.add(ls);
						receiveLocalSocket(ls, "from client");
					}
				} catch (IOException e) {
					e.printStackTrace();
				}finally{
					try {
						lss.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
		};
		t.start();
	}
	
	private void stopServer(){
		hold=false;
		try {
			lss.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
		Log.i(getClass().getName(), "stopServer.");
	}
	
	private void startClient() {
		Log.i(getClass().getName(), "startClient...");
		
		LocalSocketAddress endpoint = new LocalSocketAddress(NAME);
		clientLocalSocket1 = new LocalSocket();
		try {
			clientLocalSocket1.connect(endpoint);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		Log.d(getClass().getName(), lss.getFileDescriptor().toString());
		
		this.receiveLocalSocket(clientLocalSocket1, "to client1");
		
		clientLocalSocket2 = new LocalSocket();
		try {
			clientLocalSocket2.connect(endpoint);
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		Log.d(getClass().getName(), lss.getFileDescriptor().toString());
		
		this.receiveLocalSocket(clientLocalSocket2, "to client2");
	}
	
	private void receiveLocalSocket(final LocalSocket ls, final String title){
		Thread readThread = new Thread(){
			public void run(){
				try {
					InputStream is = ls.getInputStream();
					byte[] buffer = new byte[100];
					int len=0;
					while((len=is.read(buffer))!=-1){
						Log.i(title, new String(buffer,0,len));
					}
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		};
		readThread.start();
	}

	private void sendLocalSocket(LocalSocket ls,String str) {
		try {
			OutputStream os = ls.getOutputStream();
			os.write(str.getBytes());
			os.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
